/**
 * 
 */
package db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import db.DBHelper;

/**
 * @author Andrew
 * 
 */
public class Login {

	// set connection to DBHelper
	DBHelper helper = new DBHelper();
	
	
	private PreparedStatement validateUserStatement;

	public Login() {
	}

	// return 1 if valid user, return 0 if not valid user
	public int validateUserLogin(String phoneNumber, String userPassword) {
		int validUser = 0;
		String cleanPhoneNumber = "";
		ResultSet rs = null;
		Connection conn = helper.connection();

		// validate there are ten digits in the cleaned phone number
		if (db.FormatAndValidation.validPhoneNumber(phoneNumber)) {

			// clean phone number - remove everything but the numbers
			cleanPhoneNumber = db.FormatAndValidation
					.cleanPhoneNumber(phoneNumber);

			System.out.println(cleanPhoneNumber);

			try {

				// returns 1 if login valid, returns 0 if login not valid
				validateUserStatement = conn
						.prepareStatement(DBHelper.validateUserStatement);
				
				System.out.println("pp");
				
				validateUserStatement.setString(1, userPassword);
				validateUserStatement.setString(2, cleanPhoneNumber);

				// System.out.println("run validateUserLogin query updated");

				rs = validateUserStatement.executeQuery();
				while (rs.next()) {
					validUser = rs.getInt("userLoginValid");
				}

			}

			catch (Exception e) {
				System.out.println("Error in validateUserLogin: "
						+ e.getClass().getName() + ":" + e.getMessage());
			} finally {
				
				DBHelper.disconnect(rs, validateUserStatement, conn);

			}
		}

		return validUser;
	}

}
